/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package idea.iquest.explorer;


import idea.de.explorer.IDataElemsTopComponent;
import idea.icci.explorer.CustomContentItemsTopComponent;
import idea.iqtitles.explorer.IQuestionTitleTopComponent;
import idea.model.dbmanager.QueryManager;
import idea.model.qnrlibrary.QuestionTitleLinkView;
import idea.model.qnrlibrary.Questionnaires;
import java.awt.event.ActionEvent;
import java.beans.IntrospectionException;
import java.beans.PropertyChangeListener;
import java.util.Date;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import org.openide.ErrorManager;
import org.openide.nodes.BeanNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.nodes.PropertySupport;
import org.openide.nodes.Sheet;
import org.openide.util.Exceptions;
import org.openide.util.lookup.Lookups;
import org.openide.windows.WindowManager;


/**
 * Sets up the child nodes for the Questionnaires OutlineView
 *
 * @author rejun001
 */
public class IQuestionnairesChildFactory extends ChildFactory<Questionnaires>
{

    private List<Questionnaires> resultList;


    /**
     * xtor.
     *
     * @param resultList
     */
    public IQuestionnairesChildFactory( List<Questionnaires> resultList )
    {
        this.resultList = resultList;
    }


    /**
     * Create the node keys.
     *
     * @param list
     * @return true always
     */
    @Override
    protected boolean createKeys( List<Questionnaires> list )
    {
        for ( Questionnaires q : resultList )
        {
            list.add( q );
        }
        return true;
    }


    /**
     * Create an individual node for the given Questionnaire
     *
     * @param key -- the Questionnaires object
     * @return
     */
    @Override
    protected Node createNodeForKey( Questionnaires key )
    {
        IQuestionnairesNode node = null;
        try
        {
            node = new IQuestionnairesNode( key );
        } catch ( Exception e )
        {
            Exceptions.printStackTrace( e );
        }
        return node;
    }


    private class IQuestionnairesNode extends BeanNode //implements PropertyChangeListener
    {
        // to use for drilldown

        private String currQnrId = null;
        private String currFormNumber = null;
        private String currSurvey = null;
        private String currRefPeriod = null;


        /**
         * xtor.
         *
         * @param bean
         * @throws IntrospectionException
         */
        public IQuestionnairesNode( Questionnaires bean ) throws IntrospectionException
        {
            super( bean , Children.LEAF , Lookups.singleton( bean ) );
            currQnrId = bean.getQnrId();
            currFormNumber = bean.getFormNumber();
            currSurvey = bean.getSurvey();
            currRefPeriod = bean.getRefPeriod();
            
            setDisplayName( bean.getSurvey() + ": " + bean.getRefPeriod() );  // This will set the contents of the first (Node) column in OutlineView.
            //setDisplayName( bean.getFormNumber() );
            setShortDescription( bean.getFormNumber() );
        }


        /**
         * Context menu. On the Node, the original Action is pulling up a
         * properties window. on a field, the original Action is a WHERE clause
         * choice. The other two (Designer and DrillDown) are added here.
         *
         * @param bln -- bln tells whether or not it's a context menu.
         * @return the array of actions for the Node.
         */
        @Override
        public Action[] getActions( boolean bln )
        {
            Action[] oldActions = super.getActions( bln );
            Action[] newActions = new Action[ oldActions.length + 1 ];
            System.arraycopy( oldActions , 0 , newActions , 0 , oldActions.length );
            //newActions[oldActions.length] = new ShowDesignerAction();
            newActions[oldActions.length] = new DrillDownAction();
            return newActions;

        }


        /**
         * Overrides the double-click (preferred) action Side effect: drill down
         * and display the next window.
         *
         * @return the properties window Action
         */
        @Override
        public Action getPreferredAction()
        {
            Action a = super.getPreferredAction(); // default is to bring up a property window
            System.out.println( "Preferred action !!! qnr_id is " + currQnrId + ", form num is " + currFormNumber );
            drillDown();
            return null; // for now, also open the properties window.  If null, don't.
        }

/**
 * TODO:  How to hook this up to override the default????
 * @return 
 */
//        @Override
//        protected Sheet createSheet()
//        {
//            Sheet sheet = Sheet.createDefault();
//            Sheet.Set set = Sheet.createPropertiesSet();
//            Questionnaires obj = getLookup().lookup( Questionnaires.class );
//
//            try
//            {
//                PropertySupport.Reflection surveyProp = new PropertySupport.Reflection( obj , String.class , "getSurvey" , null );
//                Property refPdProp = new PropertySupport.Reflection( obj , String.class , "getRefPeriod" , null );
//                Property formProp = new PropertySupport.Reflection( obj , String.class , "getFormNumber" , null );
//                Property titleProp = new PropertySupport.Reflection( obj , String.class , "getTitle" , "setTitle" );
//                Property subTitleProp = new PropertySupport.Reflection( obj , String.class , "getSubTitle" , "setSubTitle" );
//                Property createdByProp = new PropertySupport.Reflection( obj , String.class , "getCreatedBy" , "setCreatedBy" );
//                Property dateCreatedProp = new PropertySupport.Reflection( obj , Date.class , "getDateCreated" , null );
//
//                surveyProp.setName( "Survey" );
//                surveyProp.setPropertyEditorClass( StringPropertyEditor.class);
//                
//                refPdProp.setName( "Ref Period" );
//                formProp.setName( "Form Number" );
//                titleProp.setName( "Title" );
//                subTitleProp.setName( "Subtitle" );
//                createdByProp.setName( "Created By" );
//                dateCreatedProp.setName( "Date Created" );
//
//                set.put( surveyProp );
//                set.put( refPdProp );
//                set.put( formProp );
//                set.put( titleProp );
//                set.put( subTitleProp );
//                set.put( createdByProp );
//                set.put( dateCreatedProp );
//
//            } catch ( Exception e )
//            {
//                ErrorManager.getDefault();
//            }
//            
//            sheet.put( set);
//            return sheet;
//        }


        /**
         *
         */
        private void closeQNRChildWindows()
        {
            CustomContentItemsTopComponent ccitc = (CustomContentItemsTopComponent) WindowManager.getDefault()
                    .findTopComponent( "CustomContentItemsTopComponent" );
            IDataElemsTopComponent detc = (IDataElemsTopComponent) WindowManager.getDefault()
                    .findTopComponent( "IDataElemsTopComponent" );
            ccitc.close();
            detc.close();
        }


        /**
         *
         */
        private void drillDown()
        {
            List<QuestionTitleLinkView> qTitles = QueryManager.getQuestionTitles( currQnrId );

            closeQNRChildWindows();
            /**
             * drill down: go find the QuestionTitle top component, populate it
             * with this questionnaires qts and open it.
             */
            IQuestionTitleTopComponent iqttc = (IQuestionTitleTopComponent) WindowManager.getDefault()
                    .findTopComponent( "IQuestionTitleTopComponent" );

            iqttc.displayQuestionTitles( qTitles , currSurvey , currRefPeriod , currFormNumber );
            iqttc.open();
            iqttc.requestActive();
        }


        /**
         *
         */
        private class DrillDownAction extends AbstractAction
        {

            public DrillDownAction()
            {
                putValue( NAME , "Drill Down" );
            }


            @Override
            public void actionPerformed( ActionEvent e )
            {

                drillDown();
            }

        }
    }
}
